<template>
  <div class="address-container">
    <div class="mem_tit">收货地址</div>

    <!-- 地址列表 -->
    <div class="address" v-for="(address, index) in addressList" :key="address.id" :class="{ 'default-address': address.isDefault === 1 }">
      <div class="a_close">
        <a href="#" @click.prevent="deleteAddress(address.id)">
          <img src="/images/a_close.png" />
        </a>
      </div>
      <table border="0" class="add_t" align="center" style="width:98%; margin:10px auto;" cellspacing="0" cellpadding="0">
        <tbody>
          <tr>
            <td align="right" width="80">收货人：</td>
            <td>{{ address.receiveName }}</td>
          </tr>
          <tr>
            <td align="right" width="80">手机号：</td>
            <td>{{ address.mobile }}</td>
          </tr>
          <tr>
            <td align="right" width="80">地址：</td>
            <td>{{ address.address }}</td>
          </tr>
          <tr>
            <td align="right">备注：</td>
            <td>{{ address.remark }}</td>
          </tr>
          <tr v-if="address.isDefault === 1">
            <td align="right">状态：</td>
            <td><span class="default-tag">默认地址</span></td>
          </tr>
        </tbody>
      </table>
      <p align="right">
        <a href="#" style="color:#ff4e00;" @click.prevent="setDefault(address.id)" v-if="address.isDefault !== 1">设为默认</a>&nbsp; &nbsp; &nbsp; &nbsp; 
        <a href="#" style="color:#ff4e00;" @click.prevent="editAddress(index)">编辑</a>&nbsp; &nbsp; &nbsp; &nbsp; 
      </p>
    </div>

    <!-- 添加新地址 -->
    <div class="mem_tit">
      添加新地址
    </div>

    <!-- 地址表单 - 始终显示 -->
    <div class="address-form">
      <table border="0" class="add_tab" style="width:930px;" cellspacing="0" cellpadding="0">
        <tbody>
          <tr>
            <td align="right">收货人姓名</td>
            <td style="font-family:'宋体';">
              <input type="text" v-model="form.name" class="add_ipt" />（必填）
            </td>
            <td align="right">详细地址</td>
            <td style="font-family:'宋体';">
              <input type="text" v-model="form.detailAddress" class="add_ipt" />（必填）
            </td>
          </tr>
          <tr>
            <td align="right">手机</td>
            <td style="font-family:'宋体';">
              <input type="text" v-model="form.mobile" class="add_ipt" />（必填）
            </td>
            <td align="right">备注</td>
            <td style="font-family:'宋体';">
              <input type="text" v-model="form.remark" class="add_ipt" />
            </td>
          </tr>
        </tbody>
      </table>
      <p align="right">
        <a href="#" @click.prevent="cancelEdit" v-if="isEditing">取消</a>&nbsp; &nbsp; 
        <a href="#" class="add_b" @click.prevent="saveAddress">
          {{ isEditing ? '确认修改' : '确认添加' }}
        </a>
      </p>
    </div>
  </div>
</template>

<script>
import { getAddressList, addAddress, updateAddress, deleteAddress, setDefaultAddress } from '../../api/addressApi'

export default {
  name: 'AddressManagementComponent',
  data() {
    return {
      showForm: false,
      isEditing: false,
      editIndex: -1,
      editId: null,
      form: {
        country: '0',
        province: '0',
        city: '0',
        area: '0',
        name: '',
        detailAddress: '',
        mobile: '',
        remark: ''
      },
      addressList: []
    }
  },
  mounted() {
    this.fetchAddressList()
  },
  methods: {
    async fetchAddressList() {
      try {
        const response = await getAddressList()
        // 修复：正确处理响应数据
        this.addressList = response || []
      } catch (error) {
        console.error('获取地址列表失败:', error)
      }
    },
    showAddForm() {
      this.showForm = true
      this.isEditing = false
      this.resetForm()
    },
    cancelEdit() {
      this.showForm = false
      this.isEditing = false
      this.editIndex = -1
      this.editId = null
      this.resetForm()
    },
    async saveAddress() {
      // 构建完整的地区信息
      const provinces = ['', '四川', '重庆', '北京', '云南']
      const cities = ['', '成都', '宜宾', '南充', '绵阳']
      const areas = ['', '武侯区', '成华区', '锦江区', '青羊区']
      
      let region = ''
      if (this.form.province !== '0') {
        region += provinces[this.form.province]
      }
      if (this.form.city !== '0') {
        region += cities[this.form.city]
      }
      if (this.form.area !== '0') {
        region += areas[this.form.area]
      }
      
      // 构建完整的地址信息
      const fullAddress = `${region}${this.form.detailAddress}`
      
      const addressData = {
        address: fullAddress,
        remark: this.form.remark,
        receiveName: this.form.name,
        mobile: this.form.mobile
      }
      
      try {
        if (this.isEditing) {
          // 更新地址
          await updateAddress({ ...addressData, id: this.editId })
        } else {
          // 添加新地址
          await addAddress(addressData)
        }
        
        // 保存成功后刷新列表
        await this.fetchAddressList()
        this.showForm = false
        this.isEditing = false
        this.editIndex = -1
        this.editId = null
        this.resetForm()
      } catch (error) {
        console.error('保存地址失败:', error)
        alert('保存地址失败')
      }
    },
    editAddress(index) {
      this.editIndex = index
      this.editId = this.addressList[index].id
      this.isEditing = true
      this.showForm = true
      
      const address = this.addressList[index]
      this.form.remark = address.remark
      this.form.name = address.receiveName || ''
      this.form.mobile = address.mobile || ''
    },
    async deleteAddress(id) {
      if (confirm('确定要删除这个地址吗？')) {
        try {
          await deleteAddress(id)
          // 删除成功后刷新列表
          await this.fetchAddressList()
        } catch (error) {
          console.error('删除地址失败:', error)
          alert('删除地址失败')
        }
      }
    },
    async setDefault(id) {
      try {
        await setDefaultAddress(id)
        // 设置成功后刷新列表
        await this.fetchAddressList()
        alert('已设为默认地址')
      } catch (error) {
        console.error('设置默认地址失败:', error)
        alert('设置默认地址失败')
      }
    },
    resetForm() {
      this.form = {
        country: '0',
        province: '0',
        city: '0',
        area: '0',
        name: '',
        detailAddress: '',
        mobile: '',
        remark: ''
      }
    }
  }
}
</script>

<style scoped>
.address-container {
  padding: 20px;
}

.mem_tit {
  width: 930px;
  height: 40px;
  line-height: 40px;
  background: #f0f0f0;
  margin: 10px 0;
  text-indent: 20px;
  color: #3e3e3e;
  font-size: 14px;
  border-bottom: 1px solid #dedede;
}

.address {
  width: 930px;
  border: 1px solid #dedede;
  padding: 10px;
  margin-bottom: 20px;
  position: relative;
}

.address.default-address {
  background-color: #F4E00FF;
}

.a_close {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 15px;
  height: 15px;
}

.a_close img {
  width: 15px;
  height: 15px;
}

.add_t td {
  height: 25px;
  line-height: 25px;
}

.add_tab td {
  height: 40px;
  line-height: 40px;
}

.jj {
  width: 100px;
  height: 28px;
  border: 1px solid #dedede;
  margin: 0 5px;
}

.add_ipt {
  width: 180px;
  height: 25px;
  border: 1px solid #dedede;
  line-height: 25px;
  padding: 0 5px;
  margin: 0 5px;
}

.add_b {
  display: inline-block;
  width: 100px;
  height: 28px;
  background: #ff4e00;
  color: #fff;
  text-decoration: none;
  line-height: 28px;
  text-align: center;
  border-radius: 3px;
}

.default-tag {
  background-color: #ff4e00;
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}
</style>